﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Structure.Interfaces;
using Command;

namespace Application.Controls
{
    public partial class UserInProject : System.Web.UI.UserControl
    {
        private iCommand _command = BuildCommand.Build();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataControlField DeleteButtons = new ButtonField();
                (DeleteButtons as ButtonField).CommandName = "DeleteRow";
                (DeleteButtons as ButtonField).ButtonType = ButtonType.Image;
                (DeleteButtons as ButtonField).ImageUrl = "~/images/delete.png";
                UsersInProjectGridView.Columns.Add(DeleteButtons);

                DataTable dt = _command.UserList();
                NewUser.DataSource = dt;
                NewUser.DataTextField = "Полное имя";
                NewUser.DataValueField = "#";
                NewUser.DataBind();


            }

            if (!String.IsNullOrEmpty(ProjectId.Text))
            {
                UsersInProjectGridView.DataSource = _command.GetAllUsersInProjects(ProjectId.Text);
                UsersInProjectGridView.DataBind();
            }
        }

        protected void AddUser_Click(object sender, EventArgs e)
        {
            _command.AddUserInProject(NewUser.SelectedValue, ProjectId.Text);

            UsersInProjectGridView.DataSource = _command.GetAllUsersInProjects(ProjectId.Text);
            UsersInProjectGridView.DataBind();
        }

        protected void UsersInProjectGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteRow")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                DataTable dt = UsersInProjectGridView.DataSource as DataTable;

                string id_user = dt.Rows[index]["#"].ToString();

                _command.DeleteUserFromProject(id_user, ProjectId.Text);

                UsersInProjectGridView.DataSource = _command.GetAllUsersInProjects(ProjectId.Text);
                UsersInProjectGridView.DataBind();
            }
        }

        public void Init(string id_project)
        {
            ProjectId.Text = id_project;

            UserInProjectForm.Visible = true;

            UsersInProjectGridView.DataSource = _command.GetAllUsersInProjects(ProjectId.Text);
            UsersInProjectGridView.DataBind();
        }

        protected void ProjectFormClose_Click(object sender, ImageClickEventArgs e)
        {
            UserInProjectForm.Visible = false;
        }
    }
}